package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.respons.FlowDetailRs;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 退费申请 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-04-22
 */
@RestController
@RequestMapping("/api/auditReturnPremium")
public class AuditReturnPremiumController extends BaseController {

    @Autowired
    IAuditReturnPremiumService iAuditReturnPremiumService;

    @Autowired
    IAuditFlowService iAuditFlowService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IAuditClaimService iAuditClaimService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IAuditFlowDetailService iAuditFlowDetailService;

    @Autowired
    IStaffService iStaffService;

    /**
     * 获取退费申请列表
     */
    @GetMapping("")
    public Result getAuditReturnPremiumList(@RequestParam(value = "pageNum", defaultValue = "-1", required = false) Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "-1", required = false) Integer pageSize,
                                            @RequestParam(value = "yearPart", required = false) String yearPart,
                                            @RequestParam(value = "quarterNum", required = false) String quarterNum,
                                            @RequestParam(value = "schoolId", required = false) String schoolId,
                                            @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                            @RequestParam(value = "studentName", required = false) String studentName,
                                            @RequestParam(value = "startDate", required = false) String startDate,
                                            @RequestParam(value = "endDate", required = false) String endDate,
                                            @RequestParam(value = "returnType", required = false) String returnType,// 退费类型：1全部课时，2部分课时
                                            @RequestParam(value = "status", required = false) String status // 0待处理，1已处理
    ) {

        IPage<AuditReturnPremium> iPage = new Page<>(pageNum, pageSize);

        // 判断是否为管理员，如果不是管理员，只能看跟自己相关的数据
        String adminId = String.valueOf(this.adminId);
        if (this.adminId.equals(1568138350324350975L)) {
            adminId = "0";
        }

        iAuditReturnPremiumService.getAuditReturnPremiumList(iPage, yearPart, quarterNum, schoolId, subjectsId, studentName, startDate, endDate, returnType, status, adminId);

        try {
            for (AuditReturnPremium auditClaim : iPage.getRecords()) {
                FlowDetailRs flowDetailRs = iAuditFlowService.getFlowTaskForDetail(auditClaim.getId());
                auditClaim.setFlowDetailList(flowDetailRs.getFlowRsList());// 审批流程
                auditClaim.setStayCheckNameList(flowDetailRs.getStayCheckNameList());// 待审批
            }
        } catch (Exception e) {
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 处理退费申请
     */
    @PostMapping("")
    public Result updateAuditReturnPremiumByStatus(@RequestBody AuditReturnPremium auditReturnPremiumParam) throws ParseException {
        AuditReturnPremium auditReturnPremium = iAuditReturnPremiumService.getById(auditReturnPremiumParam.getId());
        if (auditReturnPremium == null) {
            return new Result(Code.DELETE_ERROR, "", "退费申请不存在");
        }

        Long id = auditReturnPremiumParam.getId();
        Integer status = auditReturnPremiumParam.getStatus();// 0待审批，1审批通过，2审批不通过
        AuditClaim auditClaim = iAuditClaimService.getById(id);//审核前数据

        //Integer arriveStep = auditReturnPremium.getArriveStep();// 执行到了第几步

        Integer residueCourseCount = iOrderDetailService.getResidueCourseCountForSubjects1(auditReturnPremium.getSchoolId(), auditReturnPremium.getStudentId(), auditReturnPremium.getSubjectsId(), 1);
        auditReturnPremium.setResidueCourseCount(residueCourseCount);

        //auditReturnPremium.setStatus(status);
        //iAuditReturnPremiumService.updateById(auditReturnPremium);

        if (status == 1) {
            // 同意退费申请
            if (residueCourseCount == 0) {
                return new Result(Code.DELETE_ERROR, "", "该学员没有剩余课时，退费失败");
            }

            Integer lackCount = iRecordCourseService.getLackCount(auditReturnPremium.getYearPart(), auditReturnPremium.getQuarterNum(), auditReturnPremium.getSchoolId(), auditReturnPremium.getStudentId(), auditReturnPremium.getSubjectsId(), 1);
            if (lackCount > 0) {
                return new Result(Code.ERROR, "", "该学员还有请假未补的记上课，请先处理再退费");
            }

            Result rs = iAuditFlowService.completeTask(id, this.adminId);// 同意
            if (rs.getCode().equals(Code.OK)) {
                AuditClaim auditClaimNew = iAuditClaimService.getClaimOneByIdDesc(auditReturnPremium.getId());//审核后
                if (!auditClaimNew.getStatus().equals(auditReturnPremium.getStatus())) {
                    auditReturnPremium.setStatus(status);
                    iAuditReturnPremiumService.updateById(auditReturnPremium);
                }
                AuditFlowDetail auditFlowDetail = iAuditFlowDetailService.getNowStepFlowDetail(auditReturnPremium.getId(), auditClaim.getVersionNum(), auditClaim.getStepNum(), 1);
                if (auditFlowDetail.getStepNum() == 2 && auditFlowDetail.getStatus().equals(1)) {
                    // 同意转账，添加退费记录
                    iAuditReturnPremiumService.updateReturnPremium(auditReturnPremium, this.adminId);
                }
                iAuditFlowDetailService.sendRemind(id, auditFlowDetail.getStepNum());// 推送到企业微信
            } else {
                return rs;
            }
        } else if (status == 2) {
            // 拒绝退费申请
            iAuditFlowService.refuseTask(id, this.adminId);// 拒绝
            if (auditClaim != null) {
                auditClaim.setReason(auditReturnPremiumParam.getReason());// 拒绝理由
                iAuditClaimService.updateById(auditClaim);
            }
            auditReturnPremium.setStatus(status);
            iAuditReturnPremiumService.updateById(auditReturnPremium);
            return new Result(Code.OK, "", "已拒绝退费申请");
        }

        return new Result(Code.OK, "", "已同意退费申请");
    }

    /**
     * 待审批的数量
     */
    @GetMapping("/uncheckedCount")
    public Result getAuditReturnPremiumUncheckedCount(@RequestParam(value = "yearPart", required = false) String yearPart,
                                                      @RequestParam(value = "quarterNum", required = false) String quarterNum,
                                                      @RequestParam(value = "schoolId", required = false) String schoolId,
                                                      @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                                      @RequestParam(value = "studentName", required = false) String studentName,
                                                      @RequestParam(value = "startDate", required = false) String startDate,
                                                      @RequestParam(value = "endDate", required = false) String endDate,
                                                      @RequestParam(value = "returnType", required = false) String returnType,// 退费类型：1全部课时，2部分课时
                                                      @RequestParam(value = "status", required = false) String status // 0待处理，1已处理
    ) {

        IPage<AuditReturnPremium> iPage = new Page<>(-1, -1);

        Integer count = 0;

        // 判断是否为管理员，如果不是管理员，只能看跟自己相关的数据
        String adminId = String.valueOf(this.adminId);
        if (this.adminId.equals(1568138350324350975L)) {
            return new Result(Code.OK, count, "");
        }

        iAuditReturnPremiumService.getAuditReturnPremiumList(iPage, yearPart, quarterNum, schoolId, subjectsId, studentName, startDate, endDate, returnType, status, adminId);

        for (AuditReturnPremium auditClaim : iPage.getRecords()) {
            FlowDetailRs flowDetailRs = iAuditFlowService.getFlowTaskForDetail(auditClaim.getId());
            auditClaim.setFlowDetailList(flowDetailRs.getFlowRsList());// 审批流程
            auditClaim.setStayCheckNameList(flowDetailRs.getStayCheckNameList());// 待审批
        }


        return new Result(Code.OK, count, "");
    }

}
